<?php

/**
 * 用户控制器
 */

namespace App\Http\ManagerApi\Controllers;

use App\Api\BaseClass\Controller;
use App\Http\ManagerApi\Models\User;
use Illuminate\Support\Facades\Crypt;
use App\Http\ManagerApi\Models\UserToken;
use Illuminate\Support\Facades\DB;
use App\Http\ManagerApi\Classes\CommissionCalculate;
use App\Http\ManagerApi\Models\TeamMember;
use App\Http\ManagerApi\Models\SystemUser;
use App\Http\ManagerApi\Models\PlatformSetting;

class PlatformUserController extends Controller
{
    /**
     * 用户列表
     */
    public function listUser()
    {
        $rules = [
            ['offset', 'required|integer'],
            ['limit', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['id_card_no', 'string'],
            ['is_active', 'min:0|max:1'],
        ];

        $search = [
            ['where', 'user_name', 'like', '$user_name'],
            ['where', 'mobile', 'like', '$mobile'],
            ['where', 'id_card_no', 'like', '$id_card_no'],
            ['where', 'is_active', '$is_active'],
        ];

        $format = [
            'user_name' => '%$user_name%',
            'mobile' => '%$mobile%',
            'id_card_no' => '%$id_card_no%',
        ];

        $params = $this->form->camelFormOrFail($rules);

        return $this->form->getMessage(with(new User)->pagination($params, $search, $format));
    }

    /**
     * 用户详情
     */
    public function userDetail()
    {
        $rules = [['id', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        return $this->form->getMessage(User::find($params['id']));
    }

    /**
     * 更新信息
     */
    public function updateUser()
    {
        $rules = [
            ['id', 'required|integer'],
            ['user_name', 'string'],
            ['mobile', 'string'],
            ['id_card_no', 'string'],
            ['password', 'string|between:4,12'],
            ['card_no', 'string'],
            ['address', 'string'],
        ];

        $format = ['password' => function ($key, &$value) {
            $value = Crypt::encryptString($value);
            return $key;
        }];

        $params = $this->form->camelFormOrFail($rules, $format);

        return $this->form->updateMessage(User::findOrFail($params['id'])->update($params));
    }

    /**
     * 删除用户
     */
    public function deleteUser()
    {
        $rules = [['id', 'required|integer']];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);
        if ($user->is_active == 1) {
            return $this->form->error('已激活用户不能删除！');
        }

        try {
            UserToken::where('uid', $user->id)->delete();
            $user->delete();
        } catch (\Exception $e) {
            return $this->form->error('删除失败，请重试');
        }

        return $this->form->success('删除成功');
    }

    /**
     * 激活
     */
    public function userAudit()
    {
        $rules = [
            ['id', 'required|integer'],
        ];

        $params = $this->form->camelFormOrFail($rules);

        $user = User::findOrFail($params['id']);
        if ($user->is_active == 1) {
            return $this->form->error('已激活，请勿重复操作');
        }

        DB::transaction(function () use ($user) {

            // 生成我的推荐码
            $max_recommend_code = User::max('my_recommend_code');
            $user->fill([
                'is_active' => 1,
                'my_recommend_code' => $max_recommend_code ? $max_recommend_code + 1 : 10001,
            ])->save();

            if (User::where('my_recommend_code', $max_recommend_code + 1)->count() > 1) {
                DB::rollback();
            }

            // 获取直属上级
            $super = User::where('my_recommend_code', $user->recommend_code)->first();
            if (isset($super)) {

                // 加入团队表
                TeamMember::create(['uid' => $super->id, 'sub_uid' => $user->id]);

                // 计算佣金
                $calculate_class = new CommissionCalculate($super->id);
                $calculate_class->calculateCommission();
            }

        }, 5);

        return $this->form->success('激活成功');
    }

    /**
     * 激活密码验证
     */
    public function passwordVerify()
    {
        $rules = [['password', 'required|between:4,12']];

        $params = $this->form->camelFormOrFail($rules);

        $en_pwd = PlatformSetting::firstOrFail()->value('activation_cipher');
        $result = $params['password'] == Crypt::decryptString($en_pwd);
        return $result ? $this->form->success() : $this->form->error();
    }
}